//==========================================================================
// Copyright (c) 2000-2007,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <psapi.h>

#include "dbg-share.h"

/*
 * Execute given command
 */
BOOL ExecuteCommand(char* cmdline, int flag, STARTUPINFO *si, PROCESS_INFORMATION *pi, bool bVerbose)
{
    ZeroMemory(si, sizeof(STARTUPINFO));
    si->cb = sizeof(STARTUPINFO);
    ZeroMemory(pi, sizeof(PROCESS_INFORMATION));
    si->dwYCountChars = 5000;
    si->dwFlags |= STARTF_USECOUNTCHARS;
    if (bVerbose) {
        si->dwYCountChars = 5000;
        si->dwFlags |= STARTF_USECOUNTCHARS;
    }
    else {
        si->dwFlags |= STARTF_USESTDHANDLES;
        // be quiet!
        si->hStdOutput = NULL;
        si->hStdInput = NULL;
        si->hStdError = NULL;
    }

    return CreateProcess(NULL,
            cmdline,     /* command line */
            NULL,    /* Security */
            NULL,    /* thread */
            TRUE,    /* inherit handles */
            flag,    /* start flags */
            NULL,    /* winenv, */
            NULL,    /* current directory */
            si, pi);
}

int share_number(int nPort)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    char* pszArgs = new char[512];
    pszArgs[0] = '\0';
    sprintf(pszArgs, "elshare.exe %d", nPort);
    int ret = ExecuteCommand(pszArgs, 0, &si, &pi, true);
    delete pszArgs;
    if (ret != 0) {
    	WaitForSingleObject(pi.hProcess, INFINITE);
    }
    return ret;
}
